import * as React from 'react';
import { Button, SwipeAction, Toast } from 'antd-mobile-v2';
import { Props, State } from '../type';
import styles from './index.module.less';
import AddModal from './component/add-modal';
import DetailModal from './component/detail-modal';
import _ from 'lodash';
import { GenerateUUID, GenerateUUID32 } from '@/utils';
import { moneyCapitalize } from '@/utils/utils';
import { DelReport } from '@/services/laber-declare';
import excelImg from '@/assets/plugins/excel.png';
import { stopBodyScroll, recoverBodyScroll } from '@/utils/index';
import { SecondConfirm } from '@/components/second-confirm';
import moment from 'moment';

export class LaberOutSiderDetail extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();
  preValue: undefined;
  provideItems: any;
  preProvideItems: any;

  constructor(props: Props) {
    super(props);
    this.preValue = undefined;
    this.preProvideItems = undefined;
    this.state = {
      showAddModal: false,
      showDetailModal: false,
      ids: [],
      values: [],
      editId: undefined,
      editIndex: undefined,
      uuid: GenerateUUID32(),
      showImportResult: {}, // 导入的明细
      delReport: false, // 是否删除导入的明细
      detailMode: 2, // 明细列表展示模式（1-导入 2-人工录入）
      currentCostTypes: [] // 当前选择的费别
    };
  }

  public componentDidMount() {
    const {
      props: { renderMode }
    } = this;
    const isEmitMode = this.isResubmit();

    if (renderMode === 'detail' || isEmitMode) {
      this.reportInfo();
    }
    if (this.props.form) {
      this.handleUpdateValues();
    } else {
      this.handleUpdateValuesDetail();
    }
  }

  public componentDidUpdate(prevProps: any) {
    const currentValue = this.props.form?.getFieldValue(this.props.code);
    if (
      !_.isEqual(
        prevProps.formValues?.[this.props.code || ''],
        this.props.formValues?.[this.props.code || '']
      ) ||
      !_.isEqual(this.preValue, currentValue)
    ) {
      this.preValue = currentValue;
      if (this.props.form) {
        if (
          !_.isEqual(
            JSON.stringify(this.state.values),
            JSON.stringify(
              this.props.form?.getFieldValue(this.props.code) || [{}]
            )
          ) &&
          _.isArray(this.props.form?.getFieldValue(this.props.code))
        ) {
          this.handleUpdateValues();
        }
      } else {
        this.handleUpdateValuesDetail();
      }
    }
  }

  componentWillUnmount() {
    recoverBodyScroll();
  }

  // 通过路由信息获取是否在修改草稿/重新提交 页面
  isResubmit = () => {
    const pathname = location.href;
    const isEmitMode = pathname.indexOf('resubmit?') > -1;
    return isEmitMode;
  };

  // 通过路由信息获取是否在详情 页面
  isDetail = () => {
    const pathname = location.href;
    const isEmitMode = pathname.indexOf('/declare/detail?') > -1;
    return isEmitMode;
  };

  getSearchName = (name) => {
    const locationStr = location.hash?.split('?')?.[1];
    const arr = locationStr?.split('&');
    const obj: any = {};
    for (let i = 0; i < arr?.length; i++) {
      const aItem = arr[i]?.split('=');
      obj[aItem[0]] = decodeURIComponent(aItem[1]);
    }
    return obj?.[name] || '';
  };

  handleUpdateValues = () => {
    const values = this.props.form?.getFieldValue(this.props.code);
    if (!_.isArray(values)) return;
    // 给每一项设置唯一的ID
    values.forEach((item: any) => {
      const id = GenerateUUID();
      if (!item.id) {
        item.id = id;
      }
    });
    const ids = values.map((item: any) => item.id);
    // values 会被清空，导致编辑时会清空原有的数据，开启宏任务来 使values 赋值操作最后执行
    const timer = setTimeout(() => {
      this.setState({
        values,
        ids
      });
      this.updateFormByValues(values);
      clearTimeout(timer);
    });
  };

  handleUpdateValuesDetail = () => {
    const values = this.props.formValues?.[this.props.code || ''] || [{}];

    if (!_.isArray(values)) return;
    values.forEach((item) => {
      const id = GenerateUUID();
      if (!item.id) {
        item.id = id;
      }
    });
    const ids = values.map((item) => item.id);
    // values 会被清空，导致编辑时会清空原有的数据，开启宏任务来 使values 赋值操作最后执行
    const timer = setTimeout(() => {
      this.setState({
        values,
        ids
      });
      this.updateFormByValues(values);
      clearTimeout(timer);
    });
  };

  setUuid = () => {
    const status = this.getSearchName('status');
    const dataId = this.getSearchName('applyId');
    const uid = this.isResubmit() && status == 0 ? dataId : this.props.uuid;
    return uid;
  };

  setTotalAmount = (values) => {
    if (!values) return;
    let totalAmount = 0;
    for (let i = 0; i < values.length; i++) {
      totalAmount += values[i].provideAmount;
    }
    if (this.state.showImportResult.totalProvideAmount) {
      totalAmount += Number(this.state.showImportResult.totalProvideAmount);
    }
    totalAmount = parseFloat(totalAmount.toFixed(2));
    const totalAmountText = moneyCapitalize(String(totalAmount));
    this.props.form?.setFieldsValue({
      [this.props.code]: {
        uuid: this.setUuid(),
        list: values,
        delReport: this.state.delReport
      },
      totalAmount: totalAmount,
      totalAmountText: totalAmountText
    });
  };

  // 修改
  onEdit = (params: any) => {
    // 恢复 body 滚动
    recoverBodyScroll();
    // if (params === 'back') {
    //   // 1.直接在页面里打开的弹框,小程序返回回调
    //   this.setState({ showAddModal: false });
    //   return;
    // }
    // if (params === 'backFromDetail') {
    //   // 2.在明细弹框中打开的弹框,小程序返回, 设置明细弹框返回回调
    //   this.setState({ showDetailModal: false });
    //   return;
    // }
    const ids = [...this.state.ids];
    const values = [...this.state.values];
    const { studentCode, ...rest } = params;

    if (Array.isArray(studentCode)) {
      studentCode.forEach((item) => {
        if (item.value == this.state.editId) {
          const index = values.findIndex((i) => {
            return i.studentCode.value == this.state.editId;
          });
          // values[index] = { id: this.state.editId, ...rest, studentName: item.studentName, studentCode: item };
          // 传-1进来 导致明细为空了
          if (index > -1) {
            values[index] = {
              id: this.state.editId,
              ...rest,
              studentName: item.studentName,
              studentCode: item
            };
          }
        } else {
          const id = GenerateUUID();
          ids.unshift(id);
          values.unshift({
            id: id,
            ...rest,
            studentName: item.studentName,
            studentCode: item
          });
        }
      });
    }
    this.setTotalAmount(values);
    this.setState({ showAddModal: false, ids, values, editIndex: undefined });
  };

  // 添加
  onAdd = (params: any) => {
    console.log('============params');
    console.log(params);

    recoverBodyScroll();
    if (params == 'back') {
      // 1.直接在页面里打开的弹框,小程序返回回调
      this.setState({ showAddModal: false });
      return;
    }
    if (params === 'backFromDetail') {
      // 2.在明细弹框中打开的弹框,小程序返回, 设置明细弹框返回回调
      this.setState({ showDetailModal: false });
      return;
    }
    const ids = [...this.state.ids];
    const values = [...this.state.values];
    const { studentCode, ...rest } = params;

    if (Array.isArray(studentCode)) {
      studentCode.forEach((item) => {
        const id = GenerateUUID();
        ids.unshift(id);
        values.unshift({
          id: id,
          ...rest,
          studentName: item.studentName,
          studentCode: item
        });
      });
    }
    this.setState({ showAddModal: false, ids, values });
    this.setTotalAmount(values);
  };

  // 删除明细的二次确认
  ensureLaberDelete = (index: number) => {
    const params = {
      buttons: [
        {
          text: '删除',
          cb: () => {
            this.onLaberDelete(index);
          }
        },
        {
          text: '取消'
        }
      ],
      message: '确认删除？'
    };
    SecondConfirm(params);
  };

  // 删除明细
  onLaberDelete = (index: number) => {
    const list = this.props?.form?.getFieldValue(this.props.code)?.list;
    let ids = [...this.state.ids];
    let values = [...this.state.values];
    if (list && list.length != this.state.values?.length) {
      values = list;
      ids = values.map((item: any) => item.id);
    }

    ids.splice(index, 1);
    values.splice(index, 1);
    this.setState({
      ids,
      values
    });
    this.setTotalAmount(values);
  };

  // 打开修改弹窗
  onLaberEdit = (index: number, item?: any) => {
    const { form, code } = this.props;
    const costType = form?.getFieldValue('costType');
    const secondCostType = form?.getFieldValue('secondCostType');
    const id = item ? item.value : undefined;
    this.setState(
      {
        showAddModal: true,
        editIndex: index,
        editId: id,
        currentCostTypes: [costType?.value, secondCostType?.value]
      },
      () => {
        const values = form?.getFieldValue(code)?.list || [];
        const ids = values.map((item: any) => item.id);
        this.setState({
          values,
          ids
        });
      }
    );
  };

  //打开添加明细弹框
  openAddModal = () => {
    const { form, code } = this.props;
    const costType = form?.getFieldValue('costType');
    const secondCostType = form?.getFieldValue('secondCostType');
    const projectAttr = this.props.form?.getFieldValue('projectAttr');
    const matterId = this.props.form?.getFieldValue('matterId');
    const relatedMattersAddList = this.props.form?.getFieldValue(
      'relatedMattersAddList'
    );
    if (!matterId && projectAttr?.value !== 'ky' && !relatedMattersAddList) {
      Toast.fail('选择关联事项后，才能添加发放明细。');
      return;
    }
    if (this.props.disabled) return;
    this.setState(
      {
        showAddModal: true,
        currentCostTypes: [costType?.value, secondCostType?.value]
      },
      () => {
        const values = form?.getFieldValue(code)?.list || [];
        const ids = values.map((item: any) => item.id);
        this.setState({
          values,
          ids
        });
      }
    );
    stopBodyScroll();
  };

  // 打开明细分页弹框
  openDetailModal = (type?: State['detailMode']) => {
    this.setState({
      showDetailModal: true,
      detailMode: type // 1-导入 2-人工录入 undefined-全部
    });
    stopBodyScroll();
  };

  // 关闭明细分页
  onCloseDetail = () => {
    this.setState({
      showDetailModal: false
    });
    recoverBodyScroll();
  };

  onChange = () => {
    //
  };

  public closest(el: any, selector: any) {
    const matchesSelector =
      el.matches ||
      el.webkitMatchesSelector ||
      el.mozMatchesSelector ||
      el.msMatchesSelector;
    while (el) {
      if (matchesSelector.call(el, selector)) {
        return el;
      }
      el = el.parentElement;
    }
    return null;
  }

  onWrapTouchStart = (e: any) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = this.closest(e.target, '.am-modal-content');
    if (!pNode) {
      e.preventDefault();
    }
  };

  // 明细添加弹框
  addModal = () => {
    // 上一次选择的标准
    const provideItemAddList =
      this.props.form.getFieldValue('provideItemAddList') || {};
    const list = provideItemAddList?.list || [];
    const preSelectStandard =
      list.length > 0 ? list[list.length - 1]?.standard : undefined;

    let totalAmount = 0;
    for (let i = 0; i < list.length; i++) {
      totalAmount += list[i].provideAmount;
    }
    if (Number(this.state.showImportResult.totalProvideAmount)) {
      totalAmount += Number(this.state.showImportResult.totalProvideAmount);
    }
    totalAmount = parseFloat(totalAmount.toFixed(2));
    const matterTotalUseAble =
      this.props.matterTotalUseAble === -1
        ? -1
        : this.props.matterTotalUseAble - totalAmount;
    const project = this.props.form.getFieldValue('projectId');
    const authorizeAmountUsable = this.props.authorizeAmountUsable;
    const matterId = this.props.form?.getFieldValue('matterId')?.value;
    const mattersList = this.props.form?.getFieldValue('relatedMattersAddList')
      ?.value;
    if (this.state.showAddModal && this.state.editIndex !== undefined) {
      const editValue = list[this.state.editIndex];

      return (
        <AddModal
          matterId={matterId}
          mattersList={mattersList}
          matterName={this.props.matterName}
          matterTotal={this.props.matterTotal}
          matterTotalUseAble={matterTotalUseAble}
          projectName={project?.text}
          authorizeAmountUsable={authorizeAmountUsable}
          renderMode={this.props.renderMode}
          onChange={this.onChange}
          preSelectStandard={preSelectStandard}
          onCloseModal={(params: any) => this.onEdit(params)}
          value={this.state.editIndex != undefined ? editValue : undefined}
          showDetailModal={this.state.showDetailModal}
          detailMode={this.state.detailMode}
          currentCostTypes={this.state.currentCostTypes}
          visible={this.state.showAddModal}
        />
      );
    }
    if (this.state.showAddModal) {
      const editValue = list[this.state.editIndex];
      return (
        <AddModal
          matterId={matterId}
          mattersList={mattersList}
          matterName={this.props.matterName}
          matterTotal={this.props.matterTotal}
          matterTotalUseAble={matterTotalUseAble}
          projectName={project?.text}
          authorizeAmountUsable={authorizeAmountUsable}
          renderMode={this.props.renderMode}
          onChange={this.onChange}
          preSelectStandard={preSelectStandard}
          onCloseModal={(params: any) => this.onAdd(params)}
          value={this.state.editIndex != undefined ? editValue : undefined}
          showDetailModal={this.state.showDetailModal}
          detailMode={this.state.detailMode}
          currentCostTypes={this.state.currentCostTypes}
          visible={this.state.showAddModal}
        />
      );
    } else {
      return null;
    }
  };

  // 明细分页弹框
  detailModal = () => {
    if (!this.state.showDetailModal) return null;
    const provideItemAddList = this.props.form.getFieldValue(
      'provideItemAddList'
    ) || { list: [] };

    return (
      <DetailModal
        renderMode={this.props.renderMode}
        form={this.props.form}
        code={this.props.code}
        actionName={this.props.actionName}
        // onChange={this.onChange}
        onCloseModal={() => this.onCloseDetail()}
        addModal={this.openAddModal}
        onLaberEdit={this.onLaberEdit}
        onLaberDelete={this.ensureLaberDelete}
        value={provideItemAddList?.list || []}
        detailMode={this.state.detailMode}
      />
    );
  };

  // 明细卡片描述
  getDescript = (el: any) => {
    const standard =
      el?.standard?.text?.split(' ')[0] || el?.standardName || '';
    const standardId = el?.standard?.value || el?.standardId;
    const price = el?.price || el?.standard?.minPrice || '';
    const unit =
      el?.unit?.text ||
      el?.standard?.text?.split(' ')[1]?.replace(/\d|-/g, '') ||
      '';
    let quantity = el?.quantity || 0;
    if (quantity % 1 !== 0) {
      quantity = <span style={{ color: '#FF8800' }}>{quantity}</span>;
    }
    if (standard && standardId) {
      return (
        <>
          {standard + ' ' + price + unit + ' *'}
          {quantity}
        </>
      );
    }
    return (
      <div style={{ color: '#FF8800' }}>
        自定义标准 {price + unit + ' *'}
        {quantity}
      </div>
    );
  };

  onOpen = () => {
    console.log('global open');
  };

  onClose = () => {
    console.log('global close');
  };

  //人工录入明细操作按钮
  rightBtnsDetail = (index: number, item: any) => {
    return [
      {
        text: '修改',
        onPress: () => this.onLaberEdit(index, item),
        style: {
          backgroundColor: '#C7C7CC',
          color: 'white',
          fontSize: '18px',
          padding: '7px'
        }
      },
      {
        text: '删除',
        onPress: () => this.ensureLaberDelete(index),
        style: {
          backgroundColor: '#FF3A30',
          color: 'white',
          fontSize: '18px',
          padding: '7px'
        }
      }
    ];
  };

  // 导入明细操作按钮
  rightBtnsReport = () => {
    return [
      {
        text: '删除',
        onPress: () => this.onReportDelete(this.state.showImportResult.id),
        style: {
          backgroundColor: '#FF3A30',
          color: 'white',
          fontSize: '18px',
          padding: '7px'
        }
      }
    ];
  };

  // 删除明细附件
  onReportDelete = async (id: any) => {
    const {
      state: { showImportResult },
      props: { form }
    } = this;
    let totalAmount = form.getFieldValue('totalAmount');
    const res = await DelReport(id);
    if (res.status !== 200) {
      Toast.fail({ content: '删除失败' });
    }

    totalAmount = totalAmount - showImportResult.totalProvideAmount;
    this.props.form.setFieldsValue({
      totalAmount,
      totalAmountText: moneyCapitalize(Number(totalAmount) + ''),
      provideItemAddList: {
        uuid: this.setUuid(),
        list: this.state.values,
        delReport: true
      }
    });

    this.setState({
      delReport: true,
      showImportResult: {}
    });
  };
  updateFormByValues = (values: any) => {
    if (!values || !values.length) return;
    let provideItemAddList =
      this.props.form?.getFieldValue('provideItemAddList') || {};

    provideItemAddList = _.isArray(provideItemAddList)
      ? {}
      : provideItemAddList;
    this.props.form?.setFieldsValue({
      provideItemAddList: {
        ...provideItemAddList,
        list: values
      }
    });
  };

  //  渲染明细列表
  renderProvideModel = () => {
    const provideItemAddList =
      this.props.form.getFieldValue('provideItemAddList') || {};

    if (
      Array.isArray(provideItemAddList.list) &&
      provideItemAddList.list.length
    ) {
      return provideItemAddList.list?.map((el: any, index: number) => {
        if (index > 4) return null;
        return (
          <div key={el.id}>
            <SwipeAction
              style={{ backgroundColor: 'gray' }}
              right={this.rightBtnsDetail(index, el?.studentCode)}
              onOpen={() => this.onOpen()}
              onClose={() => this.onClose()}
              disabled={this.props.renderMode == 'detail'}
            >
              <div className={styles.laberDetailContent}>
                <div className={styles.title}>
                  <span className={styles.titleLeft}>
                    {el?.studentCode?.studentName || el?.studentName}
                  </span>
                  <span className={styles.titleRight}>
                    {this.formatNumber(el?.provideAmount) || 0}元
                  </span>
                </div>
                <div className={styles.content}>
                  <span className={styles.contentLeft}>
                    {el?.studentCode?.departmentName || el?.departmentName}
                  </span>
                  <span className={styles.contentRight}>
                    {this.getDescript(el)}
                  </span>
                </div>
                <div className={styles.remark}>
                  工作时间：
                  {`${moment(el?.startTime || '').format(
                    'YYYY-MM-DD'
                  )}~${moment(el?.endTime || '').format('YYYY-MM-DD')}`}
                </div>
                <div className={styles.remark}>备注：{el?.remark || '无'}</div>
              </div>
            </SwipeAction>
          </div>
        );
      });
    }
    return '';
  };
  // 获取明细附件信息
  reportInfo = () => {
    const extranalData = this.props?.form?.getFormExtranalData() || {};
    const { importExtText } = extranalData;
    const importInfoObject = importExtText ? JSON.parse(importExtText) : {};
    const result = {
      message: `共导入${importInfoObject.importTotal}条数据，发放金额${importInfoObject.totalProvideAmount}元`,
      status: importInfoObject.importTotal ? 'success' : 'failed',
      id: importInfoObject?.attachmentId,
      name: importInfoObject?.attachmentName,
      totalProvideAmount: importInfoObject.totalProvideAmount
    };

    this.setState({
      showImportResult: importExtText && result.id ? result : {}
    });
    return result;
  };

  formatNumber = (num: number): number | string => {
    const length = num.toString()?.split('.')[1]?.length;
    if (length >= 2) {
      return num?.toFixed(2);
    }
    return num;
  };

  public render() {
    const { renderMode } = this.props;
    const status = Number(this.getSearchName('status'));
    const provideItemAddList =
      this.props.form.getFieldValue('provideItemAddList') || {};
    let length = 0;
    if (
      Array.isArray(provideItemAddList.list) &&
      provideItemAddList.list.length
    ) {
      length = provideItemAddList.list.length;
    }
    return (
      <div
        className={
          styles.labercardWrap +
          ' ' +
          (renderMode === 'detail' ? styles.laberCardDetail : '')
        }
        {...this.props.form?.getFieldProps(this.props.code, {
          trigger: this.onChange
        })}
      >
        <div className={styles.cardTile}>
          <span>{this.props.name}</span>
          {length > 4 && !this.isDetail() ? (
            <span
              className={styles.delBtn}
              onClick={() => this.openDetailModal(status === 0 ? 2 : undefined)}
            >
              查看全部
            </span>
          ) : null}
        </div>
        {this.renderProvideModel()}
        {renderMode !== 'detail' ? (
          <div style={{ background: '#f5f5f5', paddingBottom: '8px' }}>
            <Button onClick={this.openAddModal} className={styles.addBtn}>
              + 添加发放明细
            </Button>
          </div>
        ) : null}
        {length > 4 && this.isDetail() ? (
          <div style={{ background: '#f5f5f5', paddingBottom: '8px' }}>
            <Button
              onClick={() => this.openDetailModal(status === 0 ? 2 : undefined)}
              className={styles.addBtn}
            >
              查看全部
            </Button>
          </div>
        ) : null}
        {!this.state.showImportResult.id || status !== 0 ? null : (
          <div className={styles.reportCard}>
            <SwipeAction
              right={this.rightBtnsReport()}
              onOpen={() => this.onOpen()}
              onClose={() => this.onClose()}
              disabled={this.props.renderMode == 'detail'}
            >
              <div className={styles.fileCard}>
                <div
                  className={styles.fileTitle}
                  onClick={() => this.openDetailModal(1)}
                >
                  <img className={styles.fileImg} src={excelImg} alt='' />
                  <div className={styles.fileInfo}>
                    <span className={styles.fileName}>
                      {this.state.showImportResult.name}
                    </span>
                  </div>
                </div>
                <div>{this.state.showImportResult.message} </div>
              </div>
            </SwipeAction>
          </div>
        )}
        {this.addModal()}
        {this.detailModal()}
      </div>
    );
  }
}
